package com.tg.base.list.tgnode;

import java.util.function.Function;
import java.util.function.Supplier;

public class TgLink {

    private TgNode tail;
    private TgNode head;

    private int size = 0;

    public TgLink() {
        head = new TgNode();
        tail = new TgNode();
        head.next = null;
        tail.pre = null;
    }

    public boolean empty() {
        return head.next == null;
    }

    public void add(Supplier<TgResult> commit, Function<Object, Boolean> rollback) {
        TgNode node = new TgNode(commit, rollback);
        TgNode rnode = head;
        //如果是空链表的话插入一个节点，这个节点的pre不能指向上一个节点，必须指空
        if (this.empty()) {
            rnode.next = node;
            rnode.next.pre = null;
            tail.pre = node;
            size++;
        } else {
            while (rnode.next != null)
                rnode = rnode.next;
            rnode.next = node;
            node.pre = rnode;
            tail.pre = node;
            size++;
        }
    }


    public void print() {
        TgNode tgNode = head;

        TgNode cur;
        while ((cur = tgNode.next) != null) {

            TgResult result = cur.commit.get();
            if (!result.getDone()) {
                //失败

                TgNode prev;
                while ((prev = cur.pre) != null) {
                    Boolean rollbackDone = prev.rollback.apply(prev.result.getValue());

                    cur = prev;
                }
                break;

            }
            cur.result = result;

            tgNode = cur;
        }
    }

    public static void main(String[] args) {


        TgLink tgLink = new TgLink();
        tgLink.add(
                () -> {
                    System.out.println("A run commit: ok");
                    return TgResult.of(false, 39);
                },
                (value) -> {
                    System.out.println("A run rollback:" + value);
                    return true;
                }
        );
//        tgLink.add(
//                () -> {
//                    System.out.println("B run commit: fail");
//                    return TgResult.of(true, 40);
//                },
//                (value) -> {
//                    System.out.println("B run rollback:" + value);
//                    return true;
//                }
//        );
//        tgLink.add(
//                () -> {
//                    System.out.println("C run commit: ok");
//                    return TgResult.of(false, 41);
//                },
//                (value) -> {
//                    System.out.println("C run rollback:" + value);
//                    return true;
//                }
//        );

        tgLink.print();
    }


}
